import React, { Component } from 'react'
import { connect } from 'dva';
import api from '@/api';
import get from 'lodash/get';
import router from 'umi/router';
import Link from 'umi/link';

import { Card, Row, Col, Form, Select, Button, message, Modal } from 'antd'
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import IconButton from '@/components/IconButton';
import StandardTable from '@/components/StandardTable';
import ScrollSelect from '@/components/ScrollSelect';

import styles from './Manage.less'

const FormItem = Form.Item
const { Option } = Select
@Form.create()
@connect(({ loading, base, product }) => ({
  loading: loading.effects['productService/queryProductServices'],
  serviceTypes: base.serviceTypes,
  product: product.products
}))
class ProductBind extends Component {
  state = {
    productServices: {
      list: [],
      pagination: {}
    },
    selectedRows: []
  }
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
      width: 80,
    },
    {
      title: '服务名称',
      dataIndex: 'serviceName',
    },
    {
      title: '服务类型',
      dataIndex: 'serviceTypeName',
    },
    {
      title: '产品',
      dataIndex: 'productName',
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
    },
    {
      title: '服务编码',
      dataIndex: 'serviceCode',
    },
  ]
  calcIndex = index => {
    const { productServices } = this.props;
    let currentPage = get(productServices, 'pagination.currentPage') || 1;
    let pageSize = get(productServices, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  componentDidMount() {
    this.queryProductServices()
    this.queryServiceType()
    this.queryProducts()
  }
  queryProducts = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetch'
    })
  };
  queryServiceType = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'base/fetchServiceTypes'
    })
  }
  queryProductServices = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      let queryParams = {
        pageIndex,
        pageSize,
        ...rest,
        sort: 'createTime',
        asc: false,
      }
      if (fieldsValue.serviceId) {
        queryParams.serviceId = fieldsValue.serviceId.key
      }
      if (fieldsValue.productId) {
        queryParams.productId = fieldsValue.productId
      }
      if (fieldsValue.customerId) {
        queryParams.customerId = fieldsValue.customerId.key
      }
      if (fieldsValue.serviceType) {
        queryParams.serviceType = fieldsValue.serviceType
      }
      dispatch({
        type: 'productService/queryProductServices',
        payload: {
          queryParams
        }
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({ productServices: { list: data, pagination } })
        }
      })
    })
  }
  handleTableChange = (pagination) => {
    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.queryProductServices(params);
  }
  resetConditions = () => {
    const { form } = this.props;
    form.resetFields();
    this.queryProductServices();
  };
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleDelete = () => {
    const { selectedRows } = this.state;
    const { dispatch } = this.props;
    if (!selectedRows.length) return
    Modal.confirm({
      title: '删除提醒',
      content: '是否删除已选择产品服务',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'productService/removeProductService',
          payload: {
            pathParams: {
              id: selectedRows[0].id
            },
          }
        }).then(({ errorCode, data }) => {
          if (errorCode === 0) {
            message.success('删除成功')
            this.queryProductServices()
            this.handleSelectRows([])
          }
        })
      },
    })

  }
  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };
  queryServices = params => {
    return api.service.query({
      queryParams: params,
    });
  };
  handleCreate = () => {
    router.push('/product/bind/create')
  }
  render() {
    const { form: { getFieldDecorator }, loading, serviceTypes, product } = this.props;
    const { productServices, selectedRows } = this.state;
    return (
      <PageHeaderWrapper title="产品服务绑定">
        <Card bordered={false}>
          <div className={styles.search}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="服务">
                  {getFieldDecorator('serviceId')(
                    <ScrollSelect
                      style={{ width: '100%' }}
                      search={this.queryServices}
                      optionKey="id"
                      filterOption={false}
                      allowClear
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="服务类型">
                  {getFieldDecorator('serviceType')(
                    <Select style={{ width: '100%' }} allowClear>
                      {
                        serviceTypes.map(item => (<Option value={item.code} key={item.code}>{item.name}</Option>))
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="供应商">
                  {getFieldDecorator('customerId')(
                    <ScrollSelect
                      style={{ width: '100%' }}
                      search={this.querySuppliers}
                      optionKey="id"
                      filterOption={false}
                      allowClear
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="产品">
                  {getFieldDecorator('productId')(
                    <Select

                      allowClear
                      style={{ width: '100%' }}
                    >
                      {
                        product.list.filter(item => item.id === '10000' || item.id === '10001').map(item => (
                          <Option key={item.id}>{item.name}</Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={8} push={8} sm={24}>
                <Button onClick={this.resetConditions}>重置</Button>
                <Button type="primary" onClick={() => this.queryProductServices()}>
                  查询
              </Button>
              </Col>
            </Row>
          </div>
          <div className={styles.operate}>
            <IconButton title="添加" icon="icon-add" onClick={this.handleCreate} />
            <Link to={'/product/bind/import'} style={{ color: 'rgba(0, 0, 0, 0.65)' }}>
              <IconButton title="导入" icon="icon-import" style={{ marginLeft: 12 }} />
            </Link>
            {
              selectedRows.length === 1 &&
              <IconButton title="删除" icon="icon-delete" style={{ marginLeft: 12 }} onClick={this.handleDelete} />
            }
          </div>
          <StandardTable
            rowKey="id"
            loading={loading}
            showCheckbox
            selectedRows={selectedRows}
            data={productServices}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    )
  }
}
export default ProductBind
